package com.jili;

import com.jili.config.SpringConfig;
import com.jili.dao.StudentDao;
import com.jili.dao.UserDao;
import com.jili.entity.Dog;
import com.jili.entity.Mobile;
import com.jili.entity.Order;
import com.jili.entity.User;
import com.jili.service.StudentService;
import com.jili.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * ClassName: BeanDemo
 * Package com.jili
 * Description:
 *
 * @Author: 廖继礼
 * @Create: 2025/2/15
 * @Version: v1.0
 */
public class BeanDemo {

    @Test
    public void test_create_bean(){
        // 加载spring配置文件  目录是从src开始的
        BeanFactory context = new ClassPathXmlApplicationContext("bean1.xml");
        // 获取配置创建的对象
        Dog dog = context.getBean("dog", Dog.class);
        System.out.println(dog);
    }

    @Test
    public void test_method_injection(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml");
        UserService userService = context.getBean("userService", UserService.class);
        userService.test();
    }

    /**
     * 默认单例bean
     */
    @Test
    public void test_prototype_bean(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        User user1 = context.getBean("user", User.class);
        User user2 = context.getBean("user", User.class);
        System.out.println(user1 == user2);
    }

    @Test
    public void test_setProperty(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean3.xml");
        Mobile mobile = context.getBean(Mobile.class);
        mobile.test();
    }

    @Test
    public void test_bean_life_cycle(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean4.xml");
        Order order = context.getBean("order", Order.class);
        System.out.println("4.获取创建bean的实例对象");
        System.out.println(order);
        // 手动让bean实例销毁
        ((ClassPathXmlApplicationContext) context).close();
    }

    @Test
    public void test_autowire(){
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        StudentService studentService = context.getBean("studentService", StudentService.class);
        studentService.say();
    }





}
